/*
 * @lc app=leetcode.cn id=129 lang=javascript
 *
 * [129] 求根节点到叶节点数字之和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumNumbers = function (root) {
  let sum = 0;
  const helper = (root, cur) => {
    if (!root) return;
    cur = cur * 10 + root.val;
    if (!root.left && !root.right) {
      sum += cur;
      cur = Math.floor(cur / 10);
    }
    if (root.left) helper(root.left, cur);
    if (root.right) helper(root.right, cur);
  };
  helper(root, 0);
  return sum;
};
// @lc code=end
